package com.stary.beetlsql.generator.config.querys;

import java.util.Map;

import com.stary.beetlsql.generator.config.IDbQuery;
import com.stary.beetlsql.generator.config.rules.DBType;
import com.stary.beetlsql.generator.util.StringUtils;

/**
 * <p>oracle 查询</p>
 * @author stary {@link stary1993@qq.com}
 * @since 2019-8-5
 */
public class OracleQuery implements IDbQuery {

	@Override
	public DBType dbType() {
		return DBType.ORACLE;
	}

	@Override
	public String tablesSql(String tableName) {
		String sql = " SELECT * FROM USER_TAB_COMMENTS ";
		if (!StringUtils.isEmpty(tableName)) {
			sql += " WHERE TABLE_TYPE = 'TABLE' AND TABLE_NAME = '" + tableName + "' ";
		}
		return sql;
	}

	@Override
	public String tableFieldsSql(String tableName, String colName) {
		String sql = " SELECT A.COLUMN_NAME, CASE WHEN A.DATA_TYPE='NUMBER' THEN "
				+ "(CASE WHEN A.DATA_PRECISION IS NULL THEN A.DATA_TYPE "
				+ "WHEN NVL(A.DATA_SCALE, 0) > 0 THEN A.DATA_TYPE||'('||A.DATA_PRECISION||','||A.DATA_SCALE||')' "
				+ "ELSE A.DATA_TYPE||'('||A.DATA_PRECISION||')' END) "
				+ "ELSE A.DATA_TYPE END DATA_TYPE, B.COMMENTS,DECODE(C.POSITION, '1', 'PRI') KEY "
				+ "FROM USER_TAB_COLUMNS A INNER JOIN USER_COL_COMMENTS B ON A.TABLE_NAME = B.TABLE_NAME"
				+ " AND A.COLUMN_NAME = B.COLUMN_NAME LEFT JOIN USER_CONSTRAINTS D "
				+ "ON D.TABLE_NAME = A.TABLE_NAME AND D.CONSTRAINT_TYPE = 'P' "
				+ "LEFT JOIN USER_CONS_COLUMNS C ON C.CONSTRAINT_NAME = D.CONSTRAINT_NAME "
				+ "AND C.COLUMN_NAME=A.COLUMN_NAME WHERE A.TABLE_NAME = '" + tableName + "' ";
		if (!StringUtils.isEmpty(colName)) {
			sql += " AND A.COLUMN_NAME = '" + colName + "' ";
		}
		sql += " ORDER BY A.COLUMN_ID ";
		return sql;
	}

	@Override
	public String tableName() {

		return "TABLE_NAME";
	}

	@Override
	public String tableComment() {

		return "COMMENTS";
	}

	@Override
	public String fieldName() {

		return "COLUMN_NAME";
	}

	@Override
	public String fieldType() {

		return "DATA_TYPE";
	}

	@Override
	public String fieldComment() {

		return "COMMENTS";
	}

	@Override
	public String fieldKey() {

		return "KEY";
	}

	@Override
	public boolean isKeyIdentity(Map<?,?> results) {		
		return false;
	}


}
